package com.edais.actions;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.edais.domain.User;
import com.edais.domain.UserLDActivityInfo;
import com.edais.service.ActivityService;
import com.edais.service.UserService;
import com.edais.service.gift.GiftPackageGiftOrderService;
import com.edais.service.gift.GiftPackageOrderService;
import com.edais.service.gift.GiftPackageService;
import com.edais.service.gift.GiftService;
import com.edais.util.CommonUtil;
import com.edais.util.Consts;
import com.edais.util.JsonUtil;
import com.edais.util.Message;
import com.edais.vo.ResultMsgVo;
import com.edais.util.DES3Util;

import net.sf.json.JSONObject;
import sun.util.logging.resources.logging;

/**
 * 斐讯相关的接口
 * 
 * @author rxc 2016-11-15 17:04:41
 */
@Controller
@RequestMapping(value = "/freeComm")
public class GiftFreeCommAction {

	private static final Log logger = LogFactory.getLog(GiftFreeCommAction.class);

	@Autowired
	private ActivityService activityService;
	
	/**礼包订单相关的service**/
	@Autowired
	private	GiftPackageOrderService giftPackageOrderService;

	
	
	
	/**
	 * 查询k码激活礼包信息（斐讯接口）
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/queryGiftPackage")
	public void queryGiftPackage(HttpServletRequest request, HttpServletResponse response) {
		Map<String, String> paramsMap = new HashMap<String, String>();
		// 解密请求参数
		String logInfo="根据CardeNo查询K码礼包信息";
		String reqString = request.getQueryString();
		logger.info(logInfo+"解密前的参数reqString="+reqString);
		if (StringUtils.isBlank(reqString)) {
			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.ERROR_CODE, "", "参数异常！");
			// 处理返回结果
			CommonUtil.responseJsonNotEncrypt(result, response);
			return;
		}
		String result = "";
		try {
			
			reqString=dealRequestParm(reqString, logInfo);
		  //  reqString = DES3Util.decode(reqString);
			// 解密请求参数
			Map<String, String> paramMap = CommonUtil.decryptParamters(request);
			reqString = java.net.URLDecoder.decode(reqString, "UTF-8");
			logInfo=logInfo+"解密后的的参数reqString="+reqString;
			logger.info(logInfo);
			JSONObject jsonObj = JSONObject.fromObject(reqString);
			
			List<String> keyList = Arrays.asList("channel", "idcardNo");

			if (this.checkJsonKey(jsonObj, keyList)) {
				logger.info(logInfo+"校验参数失败，缺少参数应有参数{channel, idcardNo}实际参数"
						+ reqString);
				 result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.ERROR_CODE, "", "校验参数失败，缺少参数");
				// 处理返回结果
				 logger.info(logInfo+"校验参数失败返回result="+result);
				CommonUtil.responseJsonNotEncrypt(result, response);
				return;
			}

			// 卡号
			String idcardNo = jsonObj.getString("idcardNo");
			// 渠道
			String channel = jsonObj.getString("channel");

			paramsMap.put("channel", channel);
			paramsMap.put("idcardNo", idcardNo);
			logger.info(logInfo+"开始校验参数");
			Map<String, String> checkMap = queryReturnFinanceInfoCheck(paramsMap);
			if (null == checkMap || !Consts.SUCCESS_CODE.equals(checkMap.get("code"))) {
				result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), checkMap.get("code"), "",
						checkMap.get("message"));
				// 处理返回结果
				CommonUtil.responseJsonNotEncrypt(result, response);
				logger.info(logInfo+"校验参数失败返回result="+result);
				return;
			}
			logger.info(logInfo+"校验参数成功");
			Map<String, Object> retMap = giftPackageOrderService.queryGiftPackageOrderByCardNo(idcardNo,logInfo);
			// 处理返回结果
			result = CommonUtil.setResultStringCn(retMap, Consts.SUCCESS_CODE, "", "");
			logger.info(logInfo+"调用业务方法返回结果result="+result);
			CommonUtil.responseJsonNotEncrypt(result, response);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(logInfo+"异常:" + e.getMessage());
			result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.ERROR_CODE, "",
					Message.CnDescriptionExpression.BUSINESSE_ERROR);
			logger.info(logInfo+"异常返回结果result="+result);
			// 处理返回结果
			CommonUtil.responseJsonNotEncrypt(result, response);
		}
	}
	
	/**
	 * 冻结礼包订单（斐讯接口）
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/giftPackageFrozen")
	public void giftPackageFrozen(HttpServletRequest request, HttpServletResponse response) {
		Map<String, String> paramsMap = new HashMap<String, String>();
		// 解密请求参数
		String reqString = request.getQueryString();
		String logInfo = "冻结K码礼包订单";
		logger.info(logInfo+"解密前请求参数reqString"+reqString);
		if (StringUtils.isBlank(reqString)) {
			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.ERROR_CODE, "", "参数异常！");
			// 处理返回结果
			CommonUtil.responseJsonNotEncrypt(result, response);
			return;
		}
		String result = "";
		try {
			reqString=dealRequestParm(reqString, logInfo);
			reqString = java.net.URLDecoder.decode(reqString, "UTF-8");
			
			logInfo=logInfo+"解密后请求参数reqString"+reqString;
			logger.info(logInfo);
			JSONObject jsonObj = JSONObject.fromObject(reqString);
			
			List<String> keyList = Arrays.asList("channel", "idcardNo","autoFlg");

			if (this.checkJsonKey(jsonObj, keyList)) {
				logger.info(logInfo+"校验参数失败，缺少参数应有参数{channel, idcardNo}实际参数"
						+ reqString);
				 result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.ERROR_CODE, "", "校验参数失败，缺少参数");
				// 处理返回结果
				 logger.info(logInfo+"校验参数失败返回result="+result);
				CommonUtil.responseJsonNotEncrypt(result, response);
				return;
			}

			String channel = jsonObj.getString("channel");
			String idcardNo = jsonObj.getString("idcardNo");
			String autoFlg = jsonObj.getString("autoFlg");
			
			paramsMap.put("channel", channel);
			paramsMap.put("idcardNo", idcardNo);
			logger.info(logInfo+"开始检查参数");
			Map<String, String> checkMap = queryReturnFinanceInfoCheck(paramsMap);
			if (null == checkMap || !Consts.SUCCESS_CODE.equals(checkMap.get("code"))||StringUtils.isBlank(autoFlg)) {
				result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), checkMap.get("code"), "",
						checkMap.get("message"));
				// 处理返回结果
				CommonUtil.responseJsonNotEncrypt(result, response);
				logger.info(logInfo+"校验参数失败返回result="+result);
				return;
			}


			// 给自动处理放开时间限制
			if (!"Y".equals(autoFlg)) {
				 result= this.isHandle();
				if (StringUtils.isNotBlank(result)) {
					// 处理返回结果
					CommonUtil.responseJsonNotEncrypt(result, response);
					logger.info(logInfo+"当前时间段不能进行冻结操作，返回result="+result);
					return;
				}
			}
			
			Map<String, Object>jsonMap =giftPackageOrderService.giftPackageFrozen(idcardNo, logInfo, 2);
			result = JsonUtil.getJsonStringFromMap(jsonMap);
			CommonUtil.responseJsonNotEncrypt(result, response);
			return;

		} catch (Exception e) {
			logger.error(logInfo+"冻结异常:" + CommonUtil.printStackTraceToString(e));
			result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.ERROR_CODE, "",
					Message.CnDescriptionExpression.BUSINESSE_ERROR);
			// 处理返回结果
			CommonUtil.responseJsonNotEncrypt(result, response);
		}
	}
	
	
	
	
	
	/**
	 * 解冻礼包订单（斐讯接口）
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/giftPackageFrozenCancel")
	public void giftPackageFrozenCancel(HttpServletRequest request, HttpServletResponse response) {
		Map<String, String> paramsMap = new HashMap<String, String>();
		// 解密请求参数
		String reqString = request.getQueryString();
		String logInfo = "解冻K码礼包订单";
		logger.info(logInfo+"解密前请求参数reqString"+reqString);
		if (StringUtils.isBlank(reqString)) {
			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.ERROR_CODE, "", "参数异常！");
			// 处理返回结果
			CommonUtil.responseJsonNotEncrypt(result, response);
			return;
		}
		String result = "";
		try {
			reqString=dealRequestParm(reqString, logInfo);
			reqString = java.net.URLDecoder.decode(reqString, "UTF-8");
			logInfo=logInfo+"解密后请求参数reqString"+reqString;
			logger.info(logInfo);
			JSONObject jsonObj = JSONObject.fromObject(reqString);
			
			List<String> keyList = Arrays.asList("channel", "idcardNo","autoFlg");

			if (this.checkJsonKey(jsonObj, keyList)) {
				logger.info(logInfo+"校验参数失败，缺少参数应有参数{channel, idcardNo}实际参数"
						+ reqString);
				 result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.ERROR_CODE, "", "校验参数失败，缺少参数");
				// 处理返回结果
				 logger.info(logInfo+"校验参数失败返回result="+result);
				CommonUtil.responseJsonNotEncrypt(result, response);
				return;
			}

			String channel = jsonObj.getString("channel");
			String idcardNo = jsonObj.getString("idcardNo");
			String autoFlg = jsonObj.getString("autoFlg");
			
			paramsMap.put("channel", channel);
			paramsMap.put("idcardNo", idcardNo);
			logger.info(logInfo+"开始检查参数");
			Map<String, String> checkMap = queryReturnFinanceInfoCheck(paramsMap);
			if (null == checkMap || !Consts.SUCCESS_CODE.equals(checkMap.get("code"))||StringUtils.isBlank(autoFlg)) {
				result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), checkMap.get("code"), "",
						checkMap.get("message"));
				// 处理返回结果
				CommonUtil.responseJsonNotEncrypt(result, response);
				logger.info(logInfo+"校验参数失败返回result="+result);
				return;
			}
			logger.info(logInfo+"校验参数成功");
			// 给自动处理放开时间限制
			if (!"Y".equals(autoFlg)) {
				 result= this.isHandle();
				if (StringUtils.isNotBlank(result)) {
					// 处理返回结果
					CommonUtil.responseJsonNotEncrypt(result, response);
					logger.info(logInfo+"当前时间段不能进行解冻操作，返回result="+result);
					return;
				}
			}
			
			Map<String, Object>jsonMap =giftPackageOrderService.giftPackageFrozen(idcardNo, logInfo, 1);
			
			result = JsonUtil.getJsonStringFromMap(jsonMap);
			CommonUtil.responseJsonNotEncrypt(result, response);
			return;
			
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("礼包订单解冻异常:" + CommonUtil.printStackTraceToString(e));
			result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.ERROR_CODE, "",
					Message.CnDescriptionExpression.BUSINESSE_ERROR);
			// 处理返回结果
			CommonUtil.responseJsonNotEncrypt(result, response);
		}
	}


	/**
	 * 判断内否进行解冻冻结操作 能返回null 不能返回resulet
	 * @return
	 */
	private String isHandle() throws Exception{
		// 操作时间判定
		SimpleDateFormat ymdhmsFormat = new SimpleDateFormat("yyyyMMddHHmmss");
		SimpleDateFormat hmsFormat = new SimpleDateFormat("HH:mm");
		Date now = new Date();
		Calendar cal = Calendar.getInstance();
		cal.setTime(now);
		int nowHours = cal.get(Calendar.HOUR_OF_DAY);
		// 获取起始时间边界
		String afterTimeStr = activityService.findParamValueByName("frozen_order_after_time");//冻结金额禁止开始时间 HHMMSS
		Date afterTime = ymdhmsFormat.parse(ymdhmsFormat.format(now).substring(0, 8) + afterTimeStr);
		// 判定跨天
		// 获取结束时间边界 如果跨天且在结束范围内则起始时间日期减1
		String housNum = activityService.findParamValueByName("frozen_order_hous_num");//冻结金额禁止小时数
		cal.setTime(afterTime);
		int afterHours = cal.get(Calendar.HOUR_OF_DAY);
		int endHours = afterHours + Integer.parseInt(housNum);
		if (endHours >= 24 && endHours - 24 >= nowHours) {
			cal.add(Calendar.DATE, -1);
			afterTime = cal.getTime();
		}
		cal.setTime(afterTime);
		cal.add(Calendar.HOUR_OF_DAY, Integer.parseInt(housNum));
		Date endTime = cal.getTime();

		if (now.getTime() > afterTime.getTime() && now.getTime() < endTime.getTime()) {
			String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.ERROR_CODE, "",
					"系统时间" + hmsFormat.format(afterTime) + "~" + hmsFormat.format(cal.getTime()) + "不能进行此操作!");
			return result;
		}else{
			return null;
		}
	}
	

	/**
	 * 查询理财信息及k码操作激活状态方法数据检查
	 * 
	 * @param paramsMap
	 * @return
	 */
	private Map<String, String> queryReturnFinanceInfoCheck(Map<String, String> paramsMap) throws Exception {
		Map<String, String> resMap = new HashMap<String, String>();
		String channel = paramsMap.get("channel");
		String idcardNo = paramsMap.get("idcardNo");

		// channel
		if (StringUtils.isBlank(channel) || !"PHICOMM".equals(channel)) {
			logger.error("数据检查失败：channel为:" + channel);
			resMap.put("code", Consts.ERROR_CODE);
			resMap.put("message", "渠道参数不正确!");
			return resMap;
		}

		if (StringUtils.isBlank(idcardNo)) {
			logger.error("数据检查失败：idcardNo为:" + idcardNo);
			resMap.put("code", Consts.ERROR_CODE);
			resMap.put("message", "卡号参数不正确!");
			return resMap;
		}


		resMap.put("code", Consts.SUCCESS_CODE);
		resMap.put("message", Consts.SUCCESS_DESCRIBE);
		return resMap;
	}
	
	private  String dealRequestParm(String paramters,String logInfo) throws Exception{
		logger.info(logInfo+"处理请求参数，处理前"+paramters);
		Map<String,Object> rtnMap= new HashMap<String, Object>();
		logger.debug("请求参数列表：");
		String[] tmpArr = paramters.split("&");
		for(int i = 0; i < tmpArr.length; i++){
//			logger.debug("*************" + tmpArr[i]);
			
			String[] paramArr = tmpArr[i].split("=");
			if (paramArr.length == 1) {        // 参数值为空
				rtnMap.put(paramArr[0], "");
			} else if (paramArr.length == 2) {
				rtnMap.put(paramArr[0], paramArr[1]);
			} else {
				
			}
		}
		
		String reqString=JsonUtil.getJsonStringFromMap(rtnMap);
		logger.info(logInfo+"处理请求参数，处理后"+reqString);
		return reqString;
	}
	
	/**
	 * 
	 * @Description: 校验jsonObj里的key是否存在,有一个不存在返回true，全存在返回false
	 * @param jsonObj
	 * @param keyList
	 * @return
	 * @return boolean
	 * @author ruXinChao
	 * @date 2016-9-23 上午9:38:09
	 */
	private boolean checkJsonKey(JSONObject jsonObj, List<String> keyList) {

		for (String string : keyList) {
			if (!jsonObj.containsKey(string)) {
				return true;
			}
		}
		return false;
	}
}
